package de.pernpas.calendar;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.pernpas.calendar.entity.Event;
import de.pernpas.calendar.service.EventService;

public class ExportICS extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(ExportICS.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		res.setContentType("text/Calendar");
		res.setHeader("Content-Disposition", "attachment; filename=discoboizcal.ics");
		
		PrintWriter out = res.getWriter(); 
		out.println("BEGIN:VCALENDAR");

		out.println("PRODID:-//DisoBoiz Calendar//pernpas 1.0//DE");
		out.println("CALSCALE:GREGORIAN");
		out.println("VERSION:2.0");
		
		List<Event> eventList = EventService.getAllEvents();
		
		for (Event event : eventList) {
			
			SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
			String dateStr = "";
			try {
				dateStr = sdf.format(event.getDate());
			} catch (NullPointerException e) {
				log.severe(e.getMessage());
			}
			
			if (!dateStr.equals("")) {
				out.println("BEGIN:VEVENT");
				out.println("CATEGORIES:PERSONAL");
				out.println("DTSTART;VALUE=DATE:" + dateStr + "T200000");
				out.println("DTEND;VALUE=DATE:" + dateStr + "T230000");
				out.println("SUMMARY:" + event.getEventName());
				out.println("DESCRIPTION:" + event.getDescription().getValue());
				out.println("LOCATION:" + event.getLocation());
				//			out.println("UID:" + dateStr + "T180238Z-uidGen@192.168.2.100");
				out.println("UID:" + event.getKey().getId());
				out.println("END:VEVENT");
			}
		}
		
		out.println("END:VCALENDAR");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}
}
